/*
 * Copyright 2011 evswork Team
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *     http://www.apache.org/licenses/LICENSE-2.0
 *  
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 */

package org.evswork.getwit.smackwrap;

import javax.net.ssl.SSLSocketFactory;

import org.jivesoftware.smack.Chat;
import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.MessageListener;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.packet.Message;

import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.util.Log;

public class SmackWrapper implements MessageListener {
	private XMPPConnection connection;
	private ConnectionClient client;
	private Context ctxt;
	private SmackMessageSender sender;
	private String bot;
	private static SmackWrapper wrapper;
	//private Chat chat;
	
	public static SmackWrapper getInstance() {
		if (wrapper == null)
			wrapper = new SmackWrapper();
		return wrapper;
	}
	
	private SmackWrapper() {
		initConnection();
		sender = new SmackMessageSender(this);
		//chat = null;
	}
	
	private void initConnection()
	{
		ConnectionConfiguration connectionConfig =
			new ConnectionConfiguration("talk.google.com",5223,"gmail.com");
		connectionConfig.setSASLAuthenticationEnabled(false);
		connectionConfig.setSecurityMode(ConnectionConfiguration.SecurityMode.enabled);
		connectionConfig.setSocketFactory(SSLSocketFactory.getDefault());
		connectionConfig.setCompressionEnabled(true);
		connection = new XMPPConnection(connectionConfig);	
	}
	
	boolean conn_flag = false;
	private class ConnectThread extends Thread {
		private String user,password;
		public ConnectThread(String user,String password) {
			super();
			this.user = user;
			this.password = password;
		}

		public void run() {
			// tell client I am trying to establish connection
			client.notifyConnecting(true);
			try {
				initConnection();
				connection.connect();// connect() will perform login()
				connection.login(user,password,"Getwit");
			} catch (Exception e) {
				Log.e("Getwit", e.toString());
			}
			// tell client I have done.
			client.notifyConnecting(false);
			if (connection.isConnected())
				sender.notifyConnected();
			conn_flag = false;
		}
	}
	
	public boolean tryConnect()
	{
		String user,password;
		SharedPreferences pref;
		if ((!connection.isConnected() && !conn_flag) ||
			(connection.isConnected() && null == connection.getUser() ))
		{
			conn_flag = true;
			pref = PreferenceManager.getDefaultSharedPreferences(ctxt);
			user = pref.getString("user", "");
			password = pref.getString("password", "");
			new ConnectThread(user,password).start();
			return false;
		}
		return true;
	}
	
	public void setClient(ConnectionClient cli,Context ctxt)
	{
		this.client = cli;
		this.ctxt = ctxt;
		updateBot();
	}
	
	public void updateBot()
	{
		bot = PreferenceManager.getDefaultSharedPreferences(ctxt).getString("bot", "");
	}
	
	public Chat getChat()
	{
		if (!tryConnect())
		{
			return null;
		}
		
		//if (null == chat) {
		//	chat = connection.getChatManager().createChat(bot, this);
		//}
	
		return connection.getChatManager().createChat(bot, this);//chat;
	}
	
	public void sendMessage(String msg)
	{
		sender.post(msg);
	}

	@Override
	public void processMessage(Chat chat, Message msg) {
		client.processMessage(msg.getBody());
	}
	
	public void disconnect()
	{
		new Thread() {

			@Override
			public void run() {
				if (connection != null)
					connection.disconnect();
				getChat();
			}
			
		}
		.start();
	}
}
